#!/bin/bash
cd `dirname $0`

VERSION=$1
HOST=$2
if  [ "$HOST" == "" ]; then
 echo $0 hostname
 echo  e.g. $0 piversion 10.0.1.23 will push the current release to the Pi with the IP address 10.0.1.23
 exit 1
fi 

IP=`avahi-resolve -4 --name $HOST.local | awk '{print $2}'`
if [ "$IP" != "" ]; then
 HOST=$IP
fi



PORT=$3
if [ "$PORT" == "" ]; then
 PORT=22
fi

SSHOPTS="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"

if [ "$PASSWORD" == "" ]; then
  PASSWORD=hifiberry
fi

REMOTEVERSION=`sshpass -p "$PASSWORD" ssh -p $PORT root@$HOST cat /etc/piversion`
REMOTESUPPORTSF2FS=`sshpass -p "$PASSWORD" ssh -p $PORT root@$HOST ls /etc/f2fs`
if [ "$REMOTESUPPORTSF2FS" == "/etc/f2fs" ]; then
 REMOTESUPPORTSF2FS=1
else
 REMOTESUPPORTSF2FS=0
fi

# Not ready 
REMOTESUPPORTSF2FS=0

if [ "$REMOTEVERSION" == "" -o "$REMOTEVERSION" == "$VERSION" ]; then

 echo "Packaging Pi$VERSION release"
 ./compile $VERSION hifiberry-updater
 ./create-updater $VERSION

 echo "Copying software to $HOST"
 if [ "$REMOTESUPPORTSF2FS" == "1" ]; then 
  IMG=`ls images/ | grep updater | grep zip | grep pi$VERSION | tail -1`
  sshpass -p "$PASSWORD" scp -P $PORT $SSHOPTS images/$IMG root@$HOST:/data/updater.zip; 
 else
  IMG=`ls images/ | grep updater | grep tar.gz | grep pi$VERSION | tail -1`
  sshpass -p "$PASSWORD" scp -P $PORT $SSHOPTS images/$IMG root@$HOST:/data/updater.tar.gz;
 fi

 echo "Extracting software on $HOST"
 if [ "$NOREBOOT" == "" ]; then
  sshpass -p "$PASSWORD" ssh -p $PORT $SSHOPTS root@$HOST /opt/hifiberry/bin/extract-update --reboot
 else
  sshpass -p "$PASSWORD" ssh -p $PORT $SSHOPTS root@$HOST /opt/hifiberry/bin/extract-update
  echo "Not rebooting the system"
 fi

else
 echo "Raspberry Pi version do not match: local $VERSION != remote $REMOTEVERSION"
fi

